import { Controller } from 'egg';
import { SuccessResponse } from '../../utils/ResponseBody';
import * as moment from 'moment';

export default class WeCodeController extends Controller {
  /**
   * 根据url获取jsApi华为云签名
   */
  public async getUrlSignature() {
    const { ctx } = this;
    const { query } = ctx.request;
    const { access_token } = await this.service.weCode.getAccessToken();
    const { jstickets } = await this.service.weCode.getJsApiTicket(access_token);
    const retBody = {
      appId: this.config.appId, // 应用的client_id
      timestamp: Date.now(), // 与生成签名一致的时间戳，精确到秒十位
      noncestr: moment().format('YYYY-MM-DD'), // 服务端使用的随机串
      signature: '', // 签名信息
    };
    retBody.signature = await this.service.weCode.sign(jstickets, retBody.noncestr, retBody.timestamp, query.url);
    console.log('getUrlSignature', retBody);
    ctx.body = new SuccessResponse({ ...retBody }).toJson();
  }

  /**
   * 根据免登陆授权码获取用户信息
   */
  public async getUserInfo() {
    const { ctx } = this;
    const { query } = ctx.request;
    const { access_token } = await this.service.weCode.getAccessToken();
    const { userId } = await this.service.weCode.getUserIdByCode(access_token, query.code);
    const userInfo = await this.service.weCode.getUserInfo(access_token, userId);
    ctx.body = new SuccessResponse({ ...userInfo }).toJson();
  }
}
